use std::{fs::File, io::{self, Read,BufRead}};
use std::collections::HashMap;
pub fn converter(input: &str, tp: &str) -> String {
    let sc = read_txt("sc.txt").unwrap();
    let tc = read_txt("tc.txt").unwrap();
    let sc_word_map = build_one_2_more_map("STPhrases.txt").unwrap();
    let mut convert = OneByOneConvert{traditional: String::new(), simple: String::new()};
    if tp == "s2t" {
        convert.simple = input.to_string();
        let word_parse = convert_2_tradiontion_by_words(input, &sc_word_map); 
        if convert_2_tradiontion_by_words_flag(input, &sc_word_map) {
            return word_parse;
        }else{
            convert.s2t(sc, tc);
            return convert.traditional;
        }
    }
    else {
        convert.traditional = input.to_string();
        convert.t2s(sc, tc);
        return convert.simple;
    }
}

fn build_one_2_more_map(file_path: &str) -> io::Result<HashMap<String, String>> {
    let mut map = HashMap::new();
    let file = File::open(file_path)?;
    let reader = io::BufReader::new(file);

    for line in reader.lines() {
        let line = line?;
        let parts: Vec<&str> = line.split('\t').collect();

        if parts.len() == 2 {
            map.insert(parts[0].to_string(),parts[1].to_string()); 
        }
    }

    Ok(map)
}
fn convert_2_tradiontion_by_words_flag(simplified: &str, conversion_map: &HashMap<String, String>) -> bool{
    conversion_map.contains_key(simplified)
}
fn convert_2_tradiontion_by_words(simplified: &str, conversion_map: &HashMap<String, String>) -> String{
    conversion_map.get(simplified).cloned().unwrap_or_else(|| simplified.to_string())
}
fn read_txt(file_path: &str) -> io::Result<String> {
    let mut file = File::open(file_path)?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    Ok(content)
}
struct OneByOneConvert{
    traditional: String,
    simple: String
}

impl OneByOneConvert {
    fn s2t(& mut self, sim_list: String, trad_list: String)  {
        let mut output = String::new();
        for c in self.simple.chars() {
            if let Some(index) = sim_list.chars().position(|x| x == c) {
                output.push(trad_list.chars().nth(index).unwrap());
            }
            else {
                output.push(c);
            }
        }
        self.traditional = output;
    }

    fn t2s(& mut self, sim_list: String, trad_list: String) {
        let mut output = String::new();
        for c in self.traditional.chars() {
            if let Some(index) = trad_list.chars().position(|x| x == c) {
                output.push(sim_list.chars().nth(index).unwrap());
            }
            else {
                output.push(c);
            }
        }
        self.simple = output;
    }
}
